#include "serial.h"
#include "ui_serial.h"

#include <QDebug>

Serial::Serial(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Serial)
{
    ui->setupUi(this);

    //serial
    dsp_flag = false;
    portName = "COM1";
    baudRate = BAUD9600;

    status = DATA_HEAD1;
    rxState = 0;
    DATA_LEN_MAX = 32;

}

Serial::~Serial()
{
    delete ui;
}

void Serial::display(QString str)
{
    ui->textBrowser->insertPlainText(str);
}

void Serial::closeEvent(QCloseEvent *)
{
    dsp_flag = false;
    ui->textBrowser->clear();
}

void Serial::getSerialPortSlot(QString port, QString baud)
{
    portName = port;

    if(baud == "4800")
    {
        baudRate = BAUD4800;
    }
    else if(baud == "19200")
    {
        baudRate = BAUD19200;
    }else if(baud == "38400")
    {
        baudRate = BAUD38400;
    }else if(baud == "115200")
    {
        baudRate = BAUD115200;
    }else
    {
        baudRate = BAUD9600;
    }
}

void Serial::closeSerial()
{
    if(SerialPort->isOpen())
    {
        SerialPort->close();
        qDebug()<<"close";
    }

}

bool Serial::openSerial()
{
//    PortSettings settings;

    SerialPort = new Win_QextSerialPort(portName, QextSerialBase::EventDriven);

    if(!SerialPort->open(QIODevice::ReadWrite))
    {
        return false;
    }
    SerialPort->setBaudRate(baudRate);
    SerialPort->setDataBits(DATA_8);
    SerialPort->setStopBits(STOP_1);
    SerialPort->setParity(PAR_NONE);
    SerialPort->setFlowControl(FLOW_OFF);
    connect(SerialPort, SIGNAL(readyRead()), this, SLOT(readSerialSlot()));

    return true;
}
void Serial::readSerialSlot()
{
    dataRecBuf.clear();

    dataRecBuf = SerialPort->readAll();//read all

    bufferHandle(dataRecBuf);
}


//发送端也要做好定义，每一帧多少个字节，接收就该设置多少字节
//单片机以'\0'为截止，而QByteArray不是
void Serial::bufferHandle(const QByteArray &buf)
{
    int rxLength = 0;//考虑是否需要静态
    int test = 0;
    static int recCount = 0;

    for(int i = 0; i < buf.size(); i++)
    {
        if(rxState==0)//寻找开头AA
        {
            if(buf[i]==(char)0xAA)
            {
                rxState = 1;
                continue;
            }
        }
        else if(rxState==1)//寻找第二个55
        {
            if(buf[i]==(char)0x55)
            {
                rxState = 2;
                continue;
            }
            else
                rxState = 0;
        }
        else if(rxState==2)//接收功能字
        {
            rxState = 3;
            continue;
        }
        else if(rxState==3)//接收len
        {
            rxLength = buf[i];
            qDebug()<<"len:"<<rxLength;
            if(rxLength > 32)
            {rxState = 0;}
            else
            {
                rxState = 4;
                continue;
            }
        }
        else if(rxState==4)//开始接收数据
        {
            rxLength--;
            recDataBuf[recCount++] = buf[i];
            if(rxLength <= 0)
            {
                qDebug()<<recDataBuf[0]<<"  "<<recDataBuf[1]<<"  "<<recDataBuf[2];
                rxState = 0;
                recCount = 0;
            }
        }
//        else if(rxstate==5)//接收sum
//        {
//            RX_Data[rxcnt] = data[i];
//            if(rxcnt<=(COM_BUF_LEN-1))
//                FrameAnl(rxcnt+1);
//            //Toast.makeText(getApplicationContext(), "DataAnl OK", Toast.LENGTH_SHORT).show();
//            rxstate = 0;
//        }
#if 0
        switch(status)
        {
        case DATA_HEAD1:
            {
            if(buf[i] == (uchar)0xAA)
                status = DATA_HEAD2;
            }
            continue;
        case DATA_HEAD2:
            {
            if(buf[i] == (uchar)0x55)
            {status = DATA_FUNC; qDebug()<<"AA -> AB";}
            else
                status = DATA_HEAD1;
            }
            continue;
        case DATA_FUNC:
            {
                func = buf[i];
                status = DATA_LENGTH;
            }
            continue;
        case DATA_LENGTH:
            {
            length = buf[i];
            qDebug()<<"length:"<<length;
            if(length > DATA_LEN_MAX || length < 0)
            {
                qDebug()<<"==================================";
                status = DATA_HEAD1;
                continue;
            }
            status = DATA_START;
            }continue;
        case DATA_START:
            {
            if(byteCount < length)
            {
                dataBuffer[byteCount++] = buf[i];
                if(byteCount == length)
                {
                    byteCount = 0;
                    status = DATA_HEAD1;
//                    frameHandle(dataBuffer);
                }
            }
            else
            {
                byteCount = 0;
                status = DATA_HEAD1;
            }
            }continue;
        default: status = DATA_HEAD1;
        }
#endif
    }

}
void Serial::frameHandle(uchar *buf)
{
    qDebug()<<*buf;
}


void Serial::on_pushButton_displayON_clicked()
{
    dsp_flag = true;
}

void Serial::on_pushButton_displayOFF_clicked()
{
    dsp_flag = false;
}

void Serial::on_pushButton_clear_clicked()
{
    ui->textBrowser->clear();
}
